package com.ops.uitl.tapestry;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

import com.ops.uitl.common.Common;

public class AppFilter implements Filter {
	
	protected Logger log = Logger.getLogger(this.getClass());
	protected Common common = Common.getInstance();
	
	private String redirectPath;
	
	/**
	 * init
	 * @param config
	 * @throws ServletException
	 */
	public void init(FilterConfig config) throws ServletException { 
		redirectPath = config.getInitParameter("redirect-path");
	}
	
	/**
	 * destory
	 */
	public void destroy() {
	}
	
	/**
	 * do filter
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException,ServletException
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
			HttpServletRequest hrequest = (HttpServletRequest) request;
	        HttpServletResponse hresponse = (HttpServletResponse) response;
	        
	        String servletPath = hrequest.getServletPath();
	        String pathInfo = hrequest.getPathInfo();
	        
	        if (pathInfo == null || "".equals(pathInfo) || pathInfo.equals("/")) {
	        	if (servletPath == null || "".equals(servletPath) || servletPath.equals("/")) {
	        		redirectPath = common.getProperty("url-redirect/" + common.getProperty("url-redirect/default") + "/addr", "");
	        	} else {
	        		redirectPath = common.getProperty("url-redirect/" + servletPath + "/addr", "");
	        	}
	        	
	        	if (!"".equals(redirectPath)) {
	        		String path = hrequest.getContextPath() + redirectPath;
	        		log.debug("url-redirect " + servletPath + " to " + redirectPath);
	        		hresponse.sendRedirect(path);
	        		return;
	        	}
	        }
	        
	        chain.doFilter(request, response);
        } catch (Exception e) {
        	log.error(e);
        }
    }
	
}